package com.tsq.file.provider.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.tsq.file.api.FileInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.SignatureException;
import java.util.Date;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * @Author：dcy
 * @Description:
 * @Date: 2019/9/18 13:34
 */
@Slf4j
public class FileUtil {
    private FileUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 根据file 赋值po对象
     *
     * @param file
     * @return
     */
    public static FileInfo getFileInfo(MultipartFile file) {
        String md5 = null;
        try {
            md5 = fileMd5(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInfo fileInfo = new FileInfo();
        // 将文件的md5设置为文件表的id
        fileInfo.setId(md5);
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));
        fileInfo.setSize(file.getSize());
        fileInfo.setCreateDate(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN));
        return fileInfo;
    }

    /**
     * 文件的md5
     *
     * @param inputStream
     * @return
     */
    public static String fileMd5(InputStream inputStream) {
        try {
            return DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            log.error("fileMd5-error", e);
        }
        return null;
    }

    /**
     * MultipartFile  转  File
     *
     * @return
     * @throws SignatureException
     */
    public static File inputStreamToFile(MultipartFile mpfile) throws IOException {
        InputStream ins = null;
        File file = null;
        OutputStream os = null;
        try {
            if(mpfile.equals("")||mpfile.getSize()<=0){
                mpfile = null;
            }else {
                ins = mpfile.getInputStream();
                file = new File(mpfile.getOriginalFilename());
            }
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            os.close();
            ins.close();
        }
        return file;
    }

    /**
     * 通过发送http get 请求获取文件资源
     */
    public static void download(String url,HttpServletResponse response) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        OutputStream os = null;
        InputStream is = null;
        try {
            resp = client.newCall(req).execute();
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                is = body.byteStream();
                byte[] data = readInputStream(is);

                os = response.getOutputStream();
                os.write(data);
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            is.close();
            os.close();
        }

    }

    /**
     * 读取字节输入流内容
     */
    public static byte[] readInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            is.close();
        }
        return writer.toByteArray();
    }

    /**
     * 转换BufferedImage 数据为byte数组
     *
     * @param bImage
     * Image对象
     * @param format
     * image格式字符串.如"gif","png"
     * @return byte数组
     */
    public static byte[] imageToBytes(BufferedImage bImage, String format) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, format, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            out.close();
        }
        return out.toByteArray();
    }
}
